<template>
  <div class="app-container">
  
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button
            type="success"
            icon="plus"
            @click="handleOpenDialog()"
          >
            新增
          </el-button>
          <!-- <el-button
            type="danger"
            :disabled="selectIds.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button> -->
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column prop="id" label="Id" width="55" />
        <el-table-column prop="title" label="标题" width="150" />
        <el-table-column prop="content" label="内容"  width="150"/>
        <el-table-column prop="videoPath" label="视频地址路径" />
        <el-table-column prop="createdAt" label="开通时间" width="220" />
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>

        
      </el-table>

      <pagination
      v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="120px">
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="视频上传">
          <VideoUpload @success="handleSuccess"></VideoUpload> <!-- 使用自定义的上传组件 -->
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            placeholder="请输入内容"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "广告商管理",
  inheritAttrs: false,
});

import MemberAPI, {   ListVO } from "@/api/system/member.api";
import VideoUpload from "./VideoUpload.vue";
import { c } from "vite/dist/node/moduleRunnerTransport.d-DJ_mE5sf";

const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
});

// const queryFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
});

const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<any>({
  id: '0',
  title: '',
  content: '',
  videoPath: '',
});


const total = ref(0);
const FormRef = ref();

const Lists = ref<ListVO[]>();


// 查询
async function handleQuery() {
  console.log(queryParams)
  loading.value = true;

  try {
    queryParams.page = queryParams.pageNum;
    queryParams.limit = queryParams.pageSize;
    const data = await MemberAPI.adList(queryParams);
    console.log(data)
    if(data){
      Lists.value = data.data
      total.value = data.total || 0;
    }else {
      Lists.value = [];
      total.value = 0;
    }
  
  } finally {
    loading.value = false;
  }

  loading.value = false;
}

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   handleQuery();
// }

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

function handleSuccess(response: any) {
  console.log(response)
  if (response.status === 200) {
    formData.videoPath = response.data.url; // 假设返回的数据中包含视频路径
    //ElMessage.success("视频上传成功");
  } else {
    //ElMessage.error("视频上传失败");
  }
}


/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
async function handleOpenDialog(Id?:string,data?:any) {

  dialog.visible = true;
  if (Id) {
    dialog.title = "修改";
    Object.assign(formData, data);
  } else {
    dialog.title = "新增";
  }
}

// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;

      const formJson =  {
        "adTitle": formData.title, //广告标题
        "adContent": formData.content, //广告内容
        "adFile": formData.videoPath
      };

      if (formData.id) {
        MemberAPI.adSave(formJson)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MemberAPI.adSave(formJson)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
      loading.value = false
    }
  });
}

// 删除
function handleDelete(Id?: number) {
  const Ids = [Id || selectIds.value].join(",");

  if (!Ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      //ElMessage.success("删除成功");

      const formJson =  {
        dataId:Ids
      }
      MemberAPI.adDelete(formJson)
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery();
        })
        .finally(() => (loading.value = false));
      loading.value = false
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();

  formData.id = undefined;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}




onMounted(() => {
  handleQuery();
});
</script>
